package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysOrg;
import com.ruoyi.system.api.domain.SysOrgCertificate;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysOrgCertificateMapper;
import com.ruoyi.system.mapper.SysOrgMapper;
import com.ruoyi.system.service.ISysOrgService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 机构Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-07
 */
@Service
public class SysOrgServiceImpl implements ISysOrgService {

    private static final Logger log = LoggerFactory.getLogger(SysOrgServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysOrgMapper sysOrgMapper;

    @Autowired
    private SysDeptMapper deptMapper;
    /**
     * 查询机构和资质表信息
     *
     * @param orgId 机构主键
     * @return 机构
     */
    @Override
    public SysOrg selectSysOrgByOrgId(Long orgId) {
        SysOrg sysOrg = sysOrgMapper.selectSysOrgByOrgId(orgId);
        if (sysOrg != null) {
            //根据OrgId查询出资质列表集合
            List<SysOrgCertificate> sysOrgCertificates = sysOrgCertificateMapper.selectSysOrgCertificateListByOrgId(orgId);
            //设置到org实体属性上
            if (sysOrgCertificates != null) {
                sysOrg.setSysOrgCertificateList(sysOrgCertificates);
            }
        }
        //返回数据
        return sysOrg;

    }

    /**
     * 查询机构列表
     *
     * @param sysOrg 机构
     * @return 机构
     */
    @Override
    public List<SysOrg> selectSysOrgList(SysOrg sysOrg) {
        if (sysOrg.getKeyWord() != null && sysOrg.getKeyWord().length() >= 2) {
            sysOrg.setKeyWord1("、" + sysOrg.getKeyWord() + "、");
        }
        return sysOrgMapper.selectSysOrgList(sysOrg);
    }

    /**
     * 新增机构和资质到两个表
     *
     * @param sysOrg 机构
     * @return 结果
     */
    @Autowired
    private SysOrgCertificateMapper sysOrgCertificateMapper;

    @Autowired

    private ISysUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> insertSysOrg(SysOrg sysOrg) {
        Map<String, String> resultMap = new HashMap<String, String>();
        boolean isAdd = true;
        String[] keyWords = sysOrg.getKeyWord().trim().split("、");
        for (String keyWord : keyWords) {
            if (keyWord.length() < 2) {
                throw new ServiceException("每一个机构关键字最少2个汉字");
            }
        }
        sysOrg.setKeyWord1("、" + sysOrg.getKeyWord() + "、");
        if (sysOrg.getOrgId() != null) {
            isAdd = false;
            Integer count = jdbcTemplate.queryForObject("select count(*) from sys_org where del_flag = 0 and org_id <> ? and org_name=?", Integer.class, sysOrg.getOrgId(), sysOrg.getOrgName().trim());
            if (count > 0) {
                log.error(sysOrg.getOrgName() + "已存在!");
                throw new ServiceException(sysOrg.getOrgName() + "已存在!");
            }
            sysOrgCertificateMapper.deleteSysOrgCertificateByOrgId(sysOrg.getOrgId());
            deleteSysOrgByOrgId(sysOrg.getOrgId());
        } else {
            if (StringUtils.isEmpty(sysOrg.getUserName())) {
                log.error("管理员账号不能为空!");
                throw new ServiceException("管理员账号不能为空!");
            }
            Integer count = jdbcTemplate.queryForObject("select count(*) from sys_org where del_flag = 0 and org_name=?", Integer.class, sysOrg.getOrgName().trim());
            if (count > 0) {
                log.error(sysOrg.getOrgName() + "已存在!");
                throw new ServiceException(sysOrg.getOrgName() + "已存在!");
            }
            sysOrg.setOrgId(Seq.getSeqId());
        }
        sysOrg.setCreateUserId(SecurityUtils.getUserId());
        if (sysOrgMapper.insertSysOrg(sysOrg) > 0 && sysOrg.getSysOrgCertificateList() != null && sysOrg.getSysOrgCertificateList().size() > 0) {
            //插入到资质表中
            sysOrgCertificateMapper.addCertificateBatch(sysOrg);
        }
        if (isAdd) {
            Long deptId = insertDept(sysOrg);
            if (deptId == null || deptId == 0) {
                log.error("创建机构部门时失败，请联系管理员！");
                throw new ServiceException("创建机构部门时失败，请联系管理员！");
            }
            String userMsg = insertLoginUser(sysOrg, deptId);
            if (userMsg != null) {
                log.error(userMsg);
                throw new ServiceException(userMsg);
            }
        }
        resultMap.put("id", sysOrg.getOrgId().toString());
        return resultMap;
    }

    /**
     * 创建和机构名称相同的部门
     *
     * @param sysOrg
     * @return
     */
    public Long insertDept(SysOrg sysOrg) {
        SysDept dept = new SysDept();
        dept.setOrgId(sysOrg.getOrgId());
        dept.setAncestors("0");
        dept.setDeptName(sysOrg.getOrgName());
        dept.setLeader(sysOrg.getPersonName());
        dept.setPhone(sysOrg.getPersonPhonenumber());
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setDeptId(Seq.getSeqId());
        deptMapper.insertDept(dept);
        return dept.getDeptId();
    }

    /**
     * 判断用户的信息是否已经存在
     *
     * @param sysOrg
     * @return
     */
    private String insertLoginUser(SysOrg sysOrg, Long deptId) {
        if (StringUtils.isEmpty(sysOrg.getUserName())) return null;
        SysUser user = new SysUser();
        user.setOrgId(sysOrg.getOrgId());
        user.setDeptId(deptId);
        user.setEmail("21312321@qq.com");
        user.setNickName(sysOrg.getOrgName());
        user.setPassword("123456");
        user.setPhonenumber("11111111111");
        user.setSex(0);
        user.setStatus(0);
        user.setUserName(sysOrg.getUserName());
        Long[] roles = {2L};
        user.setRoleIds(roles);
        String msg = null;
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            msg = "新增用户'" + user.getUserName() + "'失败，登录账号已存在";
        }
        if (msg == null) {
            log.info("新增用户'" + user.getUserName() + "'成功！");
            // user.setCreateBy(SecurityUtils.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            userService.insertUser(user);
        } else
            log.error(msg);
        return msg;
    }


    /**
     * 批量逻辑删除机构
     *
     * @param orgIds 需要删除的机构主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSysOrgByOrgIds(Long[] orgIds) {
        List<Long> deptIds = jdbcTemplate.queryForList("select d.dept_id from sys_org s inner join sys_dept d on d.org_id=s.org_id where s.org_id in (" + StringUtils.join(orgIds, ",") + ")", Long.class);
        if (StringUtils.isNotEmpty(deptIds)) {
            for (Long deptId : deptIds) {
                sysOrgMapper.deleteDeptById(deptId);
            }
        }
        List<Long> userIdList = jdbcTemplate.queryForList("select u.user_id from sys_org s inner join sys_user u on u.user_name=s.user_name where s.org_id in (" + StringUtils.join(orgIds, ",") + ")", Long.class);
        if (StringUtils.isNotEmpty(userIdList)) {
            Long[] userIds = userIdList.toArray(new Long[userIdList.size()]);
            sysOrgMapper.deleteUserRole(userIds);
            sysOrgMapper.deleteUserByIds(userIds);
        }
        return sysOrgMapper.deleteSysOrgByOrgIds(orgIds);
    }

    /**
     * 删除机构信息
     *
     * @param orgId 机构主键
     * @return 结果
     */
    @Override
    public int deleteSysOrgByOrgId(Long orgId) {
        return sysOrgMapper.deleteSysOrgByOrgId(orgId);
    }

    @Override
    public List<SysOrg> orgList(SysOrg sysOrg) {
        if (StringUtils.isNotEmpty(sysOrg.getKeyWord()) && sysOrg.getKeyWord().length() >= 2) {
            sysOrg.setKeyWord1("、" + sysOrg.getKeyWord() + "、");
            return sysOrgMapper.selectOrgList(sysOrg);
        }
        return new ArrayList<>();
    }

}
